package top.ddandang.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import top.ddandang.blog.model.query.PageBean;
import top.ddandang.blog.model.pojo.Categories;
import top.ddandang.blog.mapper.CategoriesMapper;
import top.ddandang.blog.service.CategoriesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import top.ddandang.blog.utils.OssUtil;
import top.ddandang.blog.utils.RedisUtil;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author D
 * @since 2020-06-23
 */
@Service
@Slf4j
public class CategoriesServiceImpl extends ServiceImpl<CategoriesMapper, Categories> implements CategoriesService {

    @Resource
    private CategoriesMapper categoriesMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private OssUtil ossUtil;

    /**
     * Oss存放分类图片的位置
     */
    private final String path = "blog/images/categories/";
    /**
     * 全部分类数据 缓存的Key值
     */
    private final String CATEGORY_ALL_LIST_KEY = "list:categoryAll";

    @Override
    public void insertCategories(String name, String description) {

        Categories categories = new Categories();
        categories.setName(name)
                .setDescription(description);

        redisUtil.del(CATEGORY_ALL_LIST_KEY);
        //自旋锁
        while (true) {
            if(categoriesMapper.insert(categories) == 1) {
                break;
            }
        }
    }

    @Override
    public String insertCategoriesImage(MultipartFile file) {
        return ossUtil.uploadImage(file, path);
    }

    @Override
    public void insertCategories(String name, String description, String image) {
        Categories categories = new Categories();
        categories.setName(name)
                .setDescription(description)
                .setImage(image);
        redisUtil.del(CATEGORY_ALL_LIST_KEY);
        //自旋锁
        while (true) {
            if(categoriesMapper.insert(categories) == 1) {
                break;
            }
        }
    }

    @Override
    public List<Categories> listCategory(PageBean pageBean) {
        PageHelper.startPage(pageBean.getPageNo(), pageBean.getPageSize());
        return categoriesMapper.selectList(null);
    }

    @Override
    public List<Categories> allCategory() {
        log.info("进入函数！");
        List<Categories> categories = new ArrayList<>();
        //缓存存在
        if(redisUtil.hasKey(CATEGORY_ALL_LIST_KEY)) {
            log.info("缓存获取！");
            Map<Object, Object> map = redisUtil.hmget(CATEGORY_ALL_LIST_KEY);
            for(Map.Entry<Object, Object> category:map.entrySet()){
                categories.add((Categories)category.getValue());
            }
        }else {
            log.info("数据库获取！");
            Map< String,Object> map = new HashMap<>();
            categories =  categoriesMapper.selectList(null);
            for (Categories category : categories){
                map.put(category.getId().toString(),category);
            }
            redisUtil.hmset(CATEGORY_ALL_LIST_KEY,map);
        }
        System.out.println(categories);
        return categories;
    }

    @Override
    public int updateCategoryImage(Integer categoryId,String imageUrl) {
        UpdateWrapper<Categories> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", categoryId)
                .set("image", imageUrl);
        redisUtil.del(CATEGORY_ALL_LIST_KEY);
        return categoriesMapper.update(null, updateWrapper);
    }

    @Override
    public int updateCategory(Integer categoryId,String name, String description) {
        UpdateWrapper<Categories> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", categoryId)
                .set("name", name)
                .set("description", description);
        redisUtil.del(CATEGORY_ALL_LIST_KEY);
        return categoriesMapper.update(null, updateWrapper);
    }

    @Async
    @Override
    public void updateArticleAmount(Integer categoryId, Boolean add) {

        log.info(String.valueOf(categoryId));
        //先获取分类信息
        Categories categories = categoriesMapper.selectById(categoryId);

        int amount =  categories.getArticleAmount();
        if (add) {
            amount++;
        }else {
            amount--;
        }

        categoriesMapper.update(null, new UpdateWrapper<Categories>()
        .eq("id", categoryId)
        .set("article_amount", amount));
        redisUtil.del(CATEGORY_ALL_LIST_KEY);
    }
}
